package com.kasax.toolbox.ui.activity

import android.content.Intent
import android.os.Environment
import com.kasax.base.BaseActivity
import com.kasax.hilog.Logger
import com.kasax.hipermission.HiPermissionManager
import com.kasax.hipermission.PermissionProcessor
import com.kasax.toolbox.R
import com.kasax.utils.FileUtils

class MainActivity : BaseActivity() {
    private val TEST_FILE_PATH = Environment.getExternalStorageDirectory().absolutePath + "/test.txt"
    private val hiPermissionManager = HiPermissionManager.getInstance()

    override fun getLayoutId(): Int = R.layout.activity_main

    private lateinit var callback: PermissionProcessor.OnPmrmissionResultCallback

    override fun initView() {

    }

    override fun initData() {
        hiPermissionManager.attach(this)
        callback = PermissionProcessor.OnPmrmissionResultCallback {
            FileUtils.write("test1111", TEST_FILE_PATH)

            var result = FileUtils.readString(TEST_FILE_PATH)
            Logger.log("result: $result")
        }
        hiPermissionManager.injectCallback(callback)
        val hasSdkCardPermission = hiPermissionManager.hasSdkCardPermission()
        if (!hasSdkCardPermission) {
            hiPermissionManager.requestSdCardPermission()
        } else {
            callback.onDone()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        hiPermissionManager.onActivityPermissionResult(requestCode)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        hiPermissionManager.onRequestPermissionsResult(
            requestCode, permissions
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        HiPermissionManager.getInstance().detach()
    }
}